package com.smartcampusbackend.controller;

import com.smartcampusbackend.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    @Value("${alipay.notify-url}")
    private String notifyUrl;

    @Value("${alipay.return-url}")
    private String returnUrl;

    @PostMapping("/pay")
    public Map<String, Object> pay(@RequestParam String outTradeNo,
                                   @RequestParam String subject,
                                   @RequestParam String totalAmount) {
        return alipayService.createPayment(outTradeNo, subject, totalAmount);
    }

    // 支付宝异步通知
    @PostMapping("/notify")
    public String notify(HttpServletRequest request) {
        // 获取所有请求参数
        Map<String, String> params = new HashMap<>();
        request.getParameterMap().forEach((key, values) -> {
            if (values.length > 0) {
                params.put(key, values[0]);
            }
        });
        
        // 验证签名
        if (alipayService.verifyCallback(params)) {
            // 处理支付成功
            String outTradeNo = params.get("out_trade_no");
            String tradeNo = params.get("trade_no");
            String totalAmount = params.get("total_amount");
            String tradeStatus = params.get("trade_status");
            
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                alipayService.handlePaymentSuccess(outTradeNo, tradeNo, totalAmount);
            }
        }
        
        return "success";
    }

    // 支付宝同步返回
    @GetMapping("/return")
    public String returnUrl(HttpServletRequest request) {
        // 可重定向到前端支付成功页面
        return "支付成功，您可关闭本页面";
    }
    
    // 查询支付宝订单状态
    @GetMapping("/query")
    public Map<String, Object> queryOrder(@RequestParam String outTradeNo) {
        return alipayService.queryOrderStatus(outTradeNo);
    }
    
    // 检查支付宝配置
    @GetMapping("/config/check")
    public Map<String, Object> checkConfig() {
        Map<String, Object> result = new HashMap<>();
        try {
            result.put("success", true);
            result.put("appId", alipayService.getAppId());
            result.put("gatewayUrl", alipayService.getGatewayUrl());
            result.put("notifyUrl", alipayService.getNotifyUrl());
            result.put("message", "支付宝配置检查通过");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "配置检查失败: " + e.getMessage());
        }
        return result;
    }
} 